package org.nw.web.index;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nw.constants.FunRegisterConst;
import org.nw.dao.CacheUtils;
import org.nw.exception.BusiAlertException;
import org.nw.json.JacksonUtils;
import org.nw.service.sys.FunService;
import org.nw.vo.TreeVO;
import org.nw.vo.sys.FunVO;
import org.nw.web.AbsBaseController;
import org.nw.web.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统首页的操作类
 * 
 * @author xuqc
 * 
 */
@Controller
public class IndexController extends AbsBaseController {

	@Autowired
	private FunService funService;

	@RequestMapping(value = "/index.html")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		FunVO[] funVOs = funService.getTopLevelFunVOs(WebUtils.getLoginInfo().getPk_user(), WebUtils.getLoginInfo()
				.getPk_corp());
		request.setAttribute("funVOs", JacksonUtils.writeValueAsString(funVOs));
		return new ModelAndView("/index/index.jsp");
	}

	/**
	 * 查询当前用户授权的菜单
	 * 
	 * @param request
	 * @param response
	 * @param parentFunCode
	 *            父级节点编码
	 * @return
	 */
	@RequestMapping(value = "/getFunTree.json")
	@ResponseBody
	public List<TreeVO> getFunTree(HttpServletRequest request, HttpServletResponse response, String parent_id) {
		List<TreeVO> func = funService.getFunTree(WebUtils.getLoginInfo().getPk_corp(), WebUtils.getLoginInfo()
				.getPk_user(), parent_id);
		if(func == null) {
			// 返回一个null对象，js会报错
			func = new ArrayList<TreeVO>();
		} else {
			if(CacheUtils.isUseCache()) {
				// 如果是非debug模式，过滤“资源压缩”这个节点
				for(TreeVO treeVO : func) {
					if(treeVO.getCode().equals(FunRegisterConst.COMPRESSOR_FUN_CODE)) {
						func.remove(treeVO);
						break;
					}
				}
			}
		}
		return func;
	}

	/**
	 * 页面定时请求这个url，保证session不过期
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/keepSessionAlive.json")
	@ResponseBody
	public void keepSessionAlive(HttpServletRequest request, HttpServletResponse response) {

	}

	/**
	 * 检测许可证
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/checkLicense.json")
	public void checkLicense(HttpServletRequest request, HttpServletResponse response) {
		try {
			int remainDays = WebUtils.checkLicense();
			if(remainDays != -1) {
				throw new BusiAlertException("您的软件是试用版本，将在" + remainDays + "天后过期，请联系销售顾问购买许可证，感谢您的支持！");
			}
		} catch(Exception e) {
			throw new BusiAlertException(e.getMessage());
		}
	}
}
